package com.example.bloom.myapplication;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by bloom on 2017/5/26.
 * 工作报告详情（包含评论）
 */

public class WorkMessageDetailsActivity extends AppCompatActivity implements MyReportsAdapter.OnRecyclerViewItemClickListener {

    private final String TAG = getClass().getSimpleName();
    //view
    private RecyclerView mWorkRecyclerView;
    private List<ReportBean> mWorkMessageDatas = null;
    private MyReportsAdapter mWorkMessageAdapter;
    private LinearLayoutManager mLinearLayoutManager;

    private RelativeLayout mResizeLayout;
//    private ScrollView mScrollView;

    private RelativeLayout messageInputLayout;
    private EditText mInputEdit;
    private Button mSend;

    private int mCurrentItemClickPosition; // 当前点击的评论控件位置

    private int screenHeight; // 屏幕的高度
    private int editTextBodyHeight;// 编辑框的高度
    private int currentKeyboardH;// 当前键盘的高度

    private int selectItemH = 0;// 选中布局的高度
    private int replyItemH = 0; // 回复位置的高度

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_work_message_details);

        setTitle("我的报告");
        initView();
        initEvent();
        initData();
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case android.R.id.home:
                setResult(RESULT_OK);
                finish();
                break;
            default:
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    private void initView() {

        messageInputLayout = (RelativeLayout) findViewById(R.id.rl_input_content);
        mInputEdit = (EditText) findViewById(R.id.et_input);
        mSend = (Button) findViewById(R.id.bt_send);

        mResizeLayout = (RelativeLayout) findViewById(R.id.root_layout);
//        mScrollView = (ScrollView) findViewById(R.id.scrollview);
        mWorkRecyclerView = (RecyclerView) findViewById(R.id.rlv_work_report_content);

        mWorkMessageDatas = new ArrayList<>();
//        mWorkMessageAdapter = new MyReportsAdapter(this, mWorkMessageDatas);
        mWorkMessageAdapter = new MyReportsAdapter(this);
        mWorkRecyclerView.setAdapter(mWorkMessageAdapter);

        mLinearLayoutManager = new LinearLayoutManager(this);
        mLinearLayoutManager.setStackFromEnd(true);
        mWorkRecyclerView.setLayoutManager(mLinearLayoutManager);


        setViewTreeObserver();
    }

    /**
     * 获取状态栏高度
     *
     * @return
     */
    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    private void setViewTreeObserver() {

        final ViewTreeObserver swipeRefreshLayoutVTO = mResizeLayout.getViewTreeObserver();
        swipeRefreshLayoutVTO.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                Rect r = new Rect();
                mResizeLayout.getWindowVisibleDisplayFrame(r);
                int statusBarH = getStatusBarHeight();//状态栏高度
                int screenH = mResizeLayout.getRootView().getHeight();
                if (r.top != statusBarH) {
                    //在这个demo中r.top代表的是状态栏高度，在沉浸式状态栏时r.top＝0，通过getStatusBarHeight获取状态栏高度
                    r.top = statusBarH;
                }
                int keyboardH = screenH - (r.bottom - r.top);
                Log.d(TAG, "screenH＝ " + screenH + " &keyboardH = " + keyboardH + " &r.bottom=" + r.bottom + " &top=" + r.top + " &statusBarH=" + statusBarH);

                if (keyboardH == currentKeyboardH) {//有变化时才处理，否则会陷入死循环
                    return;
                }

                currentKeyboardH = keyboardH;
                screenHeight = screenH;//应用屏幕的高度
                editTextBodyHeight = mInputEdit.getHeight();

                //偏移View位置
                if (mLinearLayoutManager != null) {
                    mLinearLayoutManager.scrollToPositionWithOffset(mCurrentItemClickPosition, getViewOffset());
                }
            }
        });
    }

    private void initData() {
        mWorkMessageAdapter.getDatas().addAll(groupTestDatas());
        mWorkMessageAdapter.notifyDataSetChanged();
    }

    private void initEvent() {

        mWorkMessageAdapter.setRecycleItemClickEvent(this);
//        mResizeLayout.setKeyBordStateListener(this);
        mSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendReplyMessage(mInputEdit.getText().toString());
                hideInputLayout();
            }
        });
    }

    private List<ReportBean> groupTestDatas() {

        List<ReportBean> datas = new ArrayList<>();
        ReportBean reportBean = new ReportBean();
        reportBean.setReportType("日报");
        reportBean.setReportTime("2017-12-23 09:23");
        reportBean.setUserName("等薛蟠");
        reportBean.setReportContent("人生苦短，未来不可测，不要被未来会发生什么而困惑，需要的是过好当下，努力的朝着自己的目标奋斗");
        reportBean.setCarbonCopy("海燕");
        reportBean.setReadOver("牙膏");
        reportBean.setSubmitTime("2017-12-23 09:23");
        List<ReportReplyBean> replys = new ArrayList<>();
        ReportReplyBean reply = new ReportReplyBean();
        reply.setUserName("bloom");
        reply.setReplyId("1");
        reply.setReplyContent("开开心心工作，高高兴兴打球");
        reply.setReplyTime("2015-11-2 2:09");
        replys.add(reply);
        reportBean.setReplys(replys);
        mWorkMessageDatas.add(reportBean);
        datas.add(reportBean);

        ReportBean reportBean2 = new ReportBean();
        reportBean2.setReportType("月报");
        reportBean2.setReportTime("2011-12-23 09:23");
        reportBean2.setUserName("xxx");
        reportBean2.setReportContent("you can you up ,no can no bb!");
        reportBean2.setCarbonCopy("x海燕");
        reportBean2.setReadOver("x牙膏");
        reportBean2.setSubmitTime("2017-12-23 09:23");
        List<ReportReplyBean> replys2 = new ArrayList<>();
        ReportReplyBean reply2 = new ReportReplyBean();
        reply2.setUserName("xbloom");
        reply2.setReplyId("12");
        reply2.setReplyContent("x开开心心工作，高高兴兴打球");
        reply2.setReplyTime("2015-11-2 2:09");
        replys2.add(reply2);
        reportBean2.setReplys(replys2);
        mWorkMessageDatas.add(reportBean2);
        datas.add(reportBean2);
        return datas;
    }

    public void InsertReply(ReportReplyBean replyBean) {
//        mRelayMessageAdapter.addRelay(replyBean);
        scrollToBottom();
    }

    /**
     * 发送评论
     *
     * @param sReply
     */
    private void sendReplyMessage(String sReply) {

        ReportReplyBean reply = new ReportReplyBean();

        reply.setReplyContent(sReply);
        String replyTime = "xxx-xxx-zzz yy:mm:ss";
        reply.setReplyTime(replyTime);
        reply.setUserName("xxx");
        reply.setReplyId(String.valueOf(UUID.randomUUID()));

        ReportBean reportBean = (ReportBean) mWorkMessageAdapter.getDatas().get(mCurrentItemClickPosition);
        reportBean.getReplys().add(reply);
        mWorkMessageAdapter.notifyDataSetChanged();

//        mWorkMessageAdapter.updateMessageReley(mCurrentItemClickPosition,tmp);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

//    @Override
//    public void stateChange(int state) {
//        switch (state) {
//            case LinearLayoutView.KEYBORAD_HIDE:
//                break;
//            case LinearLayoutView.KEYBORAD_SHOW:
////                scrollToBottom();
////                scrollToPosition(mCurrentItemClickPosition);
//                break;
//        }
//    }

    public void scrollToPosition(final int position, int yOffset) {
//        mScrollView.scrollTo(0,yOffset);
//        mLinearLayoutManager.scrollToPositionWithOffset(position, 20);
    }


    /**
     * 滚动到底部
     */
    public void scrollToBottom() {

        Handler mHandler = new Handler();
        mHandler.postDelayed(new Runnable() {
            public void run() {
//                mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
//                mScrollView.scrollTo();
            }
        }, 100);
    }


    @Override
    public void onItemClick(View view, int position) {
        mCurrentItemClickPosition = position;
        showInputLayout();
    }

    /**
     * 隐藏软键盘
     *
     * @param context
     */
    public static void hideKeyboard(Context context) {
        Activity activity = (Activity) context;
        if (activity != null) {
            InputMethodManager imm =
                    (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm.isActive() && activity.getCurrentFocus() != null) {
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
            }
        }
    }

    /**
     * 显示软键盘
     *
     * @param context
     */
    public static void showKeyboard(Context context) {
        Activity activity = (Activity) context;
        if (activity != null) {
            InputMethodManager imm =
                    (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInputFromInputMethod(activity.getCurrentFocus().getWindowToken(), 0);
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public void hideInputLayout() {
        messageInputLayout.setVisibility(View.GONE);
        hideKeyboard(this);
        mInputEdit.clearFocus();
        mInputEdit.setText("");
    }

    public void showInputLayout() {
        messageInputLayout.setVisibility(View.VISIBLE);
        mInputEdit.requestFocus();
        showKeyboard(this);
    }

    /**
     * 当前选中Item的高度
     *
     * @return
     */
    private int getSelectItemHight() {

        int viewHight = 0;

        int firstPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
        //只能返回当前可见区域（列表可滚动）的子项
        View selectCircleItem = mLinearLayoutManager.getChildAt(mCurrentItemClickPosition - firstPosition);
        if (selectCircleItem != null) {
            selectItemH = selectCircleItem.getHeight();
            RecyclerView replyChildView = (RecyclerView) selectCircleItem.findViewById(R.id.rlv_reply);
            if (replyChildView != null) {
                LinearLayoutManager lm = (LinearLayoutManager) replyChildView.getLayoutManager();
//                int firstpos = lm.findFirstVisibleItemPosition();
                int Count = lm.getChildCount();
                View tmp = lm.getChildAt(0);
                replyItemH = Count * tmp.getHeight();
            }
        }
        viewHight = selectItemH + replyItemH;
        return viewHight;
    }

    /**
     * 测量偏移量
     *
     * @return
     */
    private int getViewOffset() {

        //这里如果你的listview上面还有其它占高度的控件，则需要减去该控件高度(本身的+评论模块的高度)，listview的headview除外。
        int listviewOffset = screenHeight - getSelectItemHight() - currentKeyboardH - editTextBodyHeight - 20;
        Log.i(TAG, "listviewOffset : " + listviewOffset);
        return listviewOffset;
    }

}
